<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="name"></el-input>
      </el-form-item>
      <el-form-item label="权限码" prop="perms">
        <el-input v-model="dataForm.perms" placeholder="perms"></el-input>
      </el-form-item>
      <el-form-item label="说明" prop="remark">
        <el-input
          type="textarea"
          v-model="dataForm.remark"
          placeholder="remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" v-loading="isOnSubmit">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :disabled="isOnSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getById , saveOrUpdate } from '@/api/exter/perms'
export default {
  data() {
    return {
      visible: false,
      isOnSubmit: false,
      dataForm: {
        id: null,
        name: "",
        perms: "",
        remark: ""
      },
      dataRule: {
        name: [{ required: true, message: "name不能为空", trigger: "blur" }],
        perms: [{ required: true, message: "perms不能为空", trigger: "blur" }]
      }
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id;
      this.visible = true;
      this.isOnSubmit = false;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) { 
          getById(this.dataForm.id).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.data.name;
              this.dataForm.perms = data.data.perms;
              this.dataForm.remark = data.data.remark;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.isOnSubmit = true
          const data_ = {
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              perms: this.dataForm.perms,
              remark: this.dataForm.remark
            }
          saveOrUpdate(data_).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 500
                });
                this.visible = false;
                this.$emit("refreshDataList");
              } else {
                this.$message.error(data.msg);
              }
            })
            .finally(() => {
              this.isOnSubmit = false;
            });
        }
      });
    }
  }
};
</script>
